package com.ellecity06.debugtools.adapter

import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.paging.LoadState
import androidx.paging.LoadStateAdapter
import androidx.recyclerview.widget.RecyclerView
import com.ellecity06.debugtools.databinding.DebugLoadStateViewBinding

/**
 * @author ellecity06
 * @time 2023/4/20 11:05
 * @des
 */
internal class DebugLoadStateAdapter(private val retry: (() -> Unit)? = null) :
    LoadStateAdapter<DebugLoadStateAdapter.LoadStateViewHolder>() {
    inner class LoadStateViewHolder(val binding: DebugLoadStateViewBinding) :
        RecyclerView.ViewHolder(binding.root)

    override fun onBindViewHolder(holder: LoadStateViewHolder, loadState: LoadState) {
        val binding = holder.binding
        when (loadState) {
            is LoadState.NotLoading -> {
                if (loadState.endOfPaginationReached) {
                    binding.loadMoreLoadingView.visibility = View.GONE
                    binding.loadMoreLoadFailView.visibility = View.GONE
                    binding.loadMoreLoadEndView.visibility = View.VISIBLE
                } else {
                    binding.loadMoreLoadingView.visibility = View.GONE
                    binding.loadMoreLoadFailView.visibility = View.GONE
                    binding.loadMoreLoadEndView.visibility = View.GONE
                }
            }
            is LoadState.Loading -> {
                binding.loadMoreLoadingView.visibility = View.VISIBLE
                binding.loadMoreLoadFailView.visibility = View.GONE
                binding.loadMoreLoadEndView.visibility = View.GONE
            }

            is LoadState.Error -> {
                binding.loadMoreLoadingView.visibility = View.GONE
                binding.loadMoreLoadFailView.visibility = View.VISIBLE
                binding.loadMoreLoadEndView.visibility = View.GONE
                if (retry != null) {
                    binding.loadMoreLoadFailView.setOnClickListener {
                        retry.invoke()
                    }
                }

            }
        }
    }

    override fun onCreateViewHolder(parent: ViewGroup, loadState: LoadState): LoadStateViewHolder {
        return LoadStateViewHolder(DebugLoadStateViewBinding.inflate(LayoutInflater.from(parent.context), parent, false))
    }

    override fun displayLoadStateAsItem(loadState: LoadState): Boolean {
        return super.displayLoadStateAsItem(loadState) || (loadState is LoadState.NotLoading && loadState.endOfPaginationReached)
    }
}